package com.bidianying.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.tags.Param;

import com.bidianying.dao.GewaraDao;
import com.bidianying.entity.City;
import com.bidianying.entity.ConfigVariable;
import com.bidianying.util.LoadProperties;


@Service
public class GewaraService {
	
	
	@Autowired
	private GewaraDao gewaraDao;
	
	//获取格瓦拉城市信息并且存入表
	public int saveCityIdForGewara(){
		List<City> resultList = new ArrayList<City>();
		String url = LoadProperties.getProperty("/config.properties", "gewaraCity");
		try {
			Document doc = Jsoup.connect(url).get();
			Element mainEle = doc.getElementById("piny_content");
			Elements cityHrefs = mainEle.select("a");
			for(Element city:cityHrefs){
				City cityTemp = new City();
				cityTemp.setCityId(city.attr("href"));
				cityTemp.setCityName(city.text());
				cityTemp.setCityPinyin(city.attr("href").substring(1,city.attr("href").length()));
				resultList.add(cityTemp);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		for(City city:resultList){
			String urlCity = LoadProperties.getProperty("/config.properties", "gewaraUrl")+city.getCityId();
			try {
				Response response = Jsoup.connect(urlCity).method(Method.GET).followRedirects(false).execute();
				if(response.statusCode()==200 && response.hasCookie("citycode")){
					city.setCityCode(response.cookie("citycode"));
				}else{
					city.setCityCode("");
				}
			} catch (IOException e) {
				System.out.println("异常城市："+city.getCityName());
				city.setCityCode("");
			}
		}
		return gewaraDao.saveCityIdForGewara(resultList);
	}
	public JSONArray getCity(){
		return gewaraDao.getCity();
	}
	
	/**
	 * @param	palyDate 放映日期（yyyy-MM-dd）
	 * @param	movieId 格瓦拉的电影id
	 * @param	palyDate 格瓦拉的城市代码
	 * @return  区、影院相关信息
	 */
	public Map<String,List<Map<String,String>>> getCinemaByMovie(String playDate,String movieId,String cityCode){
		Map<String,List<Map<String,String>>> resultMap = new HashMap<String,List<Map<String,String>>>();
		Map<String,String> data = new HashMap<String,String>();
		data.put("playDate", playDate);
		data.put("movieid", movieId);
		String url = LoadProperties.getProperty("/config.properties", "gewaraUrl")+"/movie/v5/getCurAllCinemaList.xhtml";
		try {
			Document doc = Jsoup.connect(url).data(data).cookie("citycode", cityCode).get();
			Element countyAreaInner = doc.getElementById("countyAreaInner");
			Elements area = countyAreaInner.select("a");
			List<Map<String,String>> areaMapList = new ArrayList<Map<String,String>>();
			List<Map<String,String>> areaCinemaMapList = new ArrayList<Map<String,String>>();
			for(Element e:area){
				Map<String,String> map = new HashMap<String,String>();
				String areaId = e.attr("id");
				String areaValue = e.text();
				map.put("areaId",areaId);
				map.put("areaValue", areaValue);
				areaMapList.add(map);
			}
			Element chooseCinema = doc.getElementById("wrapped_splayList");
			Elements cinemas = chooseCinema.select("li");
			for(Element element : cinemas){
				Map<String,String> map = new HashMap<String,String>();
				String areaId = element.attr("rel");
				String cinemaId = element.attr("cid");
				String cinemaName = element.select(".ui_edtType").first().text();
				String address = element.select(".address").first().text();
				map.put("areaId",areaId);
				map.put("cinemaId",cinemaId);
				map.put("cinemaName",cinemaName);
				map.put("address",address);
				areaCinemaMapList.add(map);
			}
			resultMap.put("areaMapList", areaMapList);
			resultMap.put("areaCinemaMapList", areaCinemaMapList);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return resultMap;
	}
	/**
	 * @param	movieId 格瓦拉的电影id
	 * @return  影片放映日期
	 */
	public List<Map<String,String>> getShowDateList(String movieId){
		List<Map<String,String>> resultList = new ArrayList<Map<String,String>>();
		String url = LoadProperties.getProperty("/config.properties", "gewaraUrl")+"/movie/v5/getCinemaPlayDateList.xhtml";
		Map<String,String> data = new HashMap<String,String>();
		data.put("movieid", movieId);
		try{
			Document doc = Jsoup.connect(url).data(data).get();
			Element playList = doc.getElementById("nav_playList");
			Elements timeOutside = playList.select("li");
			for(Element element : timeOutside){
				Element a = element.select("a").first();
				Map<String,String> map = new HashMap<String,String>();
				map.put("text", a.text());
				map.put("id", a.attr("id"));
				resultList.add(map);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return resultList;
	}
	/**
	 * @param	fyrq 放映日期
	 * @param	movieId 格瓦拉的电影id
	 * @param	cinemaId 格瓦拉的影院id
	 * @return  格瓦拉的排期信息
	 */
	public List<Map<String,String>> getCommonOpiItem(String fyrq,String movieId,String cinemaId){
		List<Map<String,String>> resultList = new ArrayList<Map<String,String>>();
		String url = LoadProperties.getProperty("/config.properties", "gewaraUrl")+"/movie/v5/getCommonOpiItem.xhtml";
		Map<String,String> data = new HashMap<String,String>();
		data.put("fyrq", fyrq);
		data.put("movieid", movieId);
		data.put("cid", cinemaId);
		try{
			Document doc = Jsoup.connect(url).data(data).get();
			Element playListBody = doc.select(".mod_bd").first();
			Elements opiTime = playListBody.select("li");
			for(Element e : opiTime){
				Map<String,String> map = new HashMap<String,String>();
				Element tdOpiTime = e.select(".opiTime").first();
				map.put("hd", tdOpiTime.select(".hd").first().text());
				map.put("bd", tdOpiTime.select(".bd").first().text());
				map.put("opiEdition", e.select(".opiEdition").first().select(".hd").first().text());
				map.put("opiRoom", e.select(".opiRoom").first().text());
				Element opiEdition = e.select(".opiEdition").first();
				map.put("ui_movieType_w", opiEdition.select(".ui_movieType_w").first().select("span").attr("class"));
				map.put("ui_movieType_w_text", opiEdition.select(".ui_movieType_w").first().text());
				resultList.add(map);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return resultList;
	}
	
	public int saveMovieInfo(){
		Set<String> movieIdSet = gewaraDao.getAllGewaraMovieId();
		String url = LoadProperties.getProperty("/config.properties", "gewaraFilm");
		int filmNum = 0;
		Map<String,String> data = new HashMap<String,String>();
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		String citycode ="440300";
		for(int i = 0;i<=filmNum/10;i++){
			try {
				data.put("pageNo",i+"");
				Document doc = Jsoup.connect(url).data(data).cookie("citycode", citycode).get();
				Element filmNumEle = doc.getElementById("keyNum_mpiMovieCount");
				//影片总数
				filmNum = Integer.parseInt(filmNumEle.text());
				//解析影片
				Elements effectLi = doc.getElementsByClass("effectLi");
				for(Element ele : effectLi){
					Map<String,String> map = new HashMap<String,String>();
					//影片信息
					Element title = ele.select("h2").first();
					map.put("title", title.text());
					String href = title.select("a").first().attr("href");
					String movieId = href.substring(7);
					map.put("movieid", movieId);
					if(!movieIdSet.contains(movieId)){
						list.add(map);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
				return 0;
			}
		}
		return gewaraDao.saveMovieInfoForGewara(list);
	}
	//获取格瓦拉的价格和购票链接
	public Map<String,Map<String,String>> getPriceHref(String fyrq,String movieId,String cinemaId){
		Map<String,Map<String,String>> resultMap = new HashMap<String,Map<String,String>>();
		String url = LoadProperties.getProperty("/config.properties", "gewaraUrl")+"/movie/v5/getCommonOpiItem.xhtml";
		Map<String,String> data = new HashMap<String,String>();
		data.put("fyrq", fyrq);
		data.put("movieid", movieId);
		data.put("cid", cinemaId);
		try{
			Document doc = Jsoup.connect(url).data(data).get();
			Element playListBody = doc.select(".mod_bd").first();
			Elements opiTime = playListBody.select("li");
			for(Element e : opiTime){
				Map<String,String> map = new HashMap<String,String>();
				Element tdOpiTime = e.select(".opiTime").first();
				String hd = tdOpiTime.select(".hd").first().text();
				Element opiPrice = e.select(".opiPrice").first();
				if(opiPrice.select(".hd").first()==null){
					continue;
				}
				map.put("opiPrice", opiPrice.select(".hd").first().text());
				map.put("href", ConfigVariable.gewaraUrl+e.select(".opiurl").select("a").first().attr("href"));
				resultMap.put(hd, map);
			}
		}catch(Exception e){
			e.printStackTrace();
			return new HashMap<String,Map<String,String>>();
		}
		return resultMap;
	}
	
	public int saveGewaraCinemaInfo(){
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		JSONArray jsonArray = gewaraDao.getCity();
		String baseUrl = LoadProperties.getProperty("/config.properties", "gewaraUrl");
		for(int j = 0;j<jsonArray.size();j++){
			int sNum = 0;
			JSONObject obj = jsonArray.getJSONObject(j);
			String url = baseUrl+"/"+obj.getString("pinyin")+"/cinemalist";
			Map<String,String> data = new HashMap<String,String>();
			System.out.println("查找城市--"+obj.getString("name"));
			for(int i = 0;i<=sNum/10;i++){
				try {
					data.put("pageNo",i+"");
					Document doc = Jsoup.connect(url).data(data).cookie("citycode", obj.getString("code")).get();
					Element sNumElement = doc.select(".sNum").first();
					if(sNumElement==null){
						System.out.println("出错误城市-----"+obj.getString("name"));
						continue;
					}
					sNum = Integer.parseInt(sNumElement.text());
					Element cinemaListAreaElement = doc.getElementById("cinemaListArea");
					Elements lis = cinemaListAreaElement.select(".effectLi");
					for(Element ele : lis){
						Map<String,String> map = new HashMap<String,String>();
						Element uiText = ele.select(".ui_text").first();
						Element cinema = uiText.select(".title").select("a").first();
						map.put("title", cinema.attr("title"));
						String href = cinema.attr("href");
						map.put("cinemaCode", href.substring(8));
						Element mt10 = uiText.select(".mt10").first();
						map.put("address", mt10.text());
						map.put("regionName", mt10.select("a").first().text());
						map.put("cityPinyin", obj.getString("pinyin"));
						list.add(map);
					}
					
				} catch (IOException e) {
					System.out.println("出错误城市-----"+obj.getString("name"));
				}
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return gewaraDao.saveGewaraCinemaInfo(list);
	}
	
}
